<template>
  <div class="framework1">
    <!--    全部表格-->

    <!--   许可证查看界面   -->
    <div class="framework2" v-show="!clickTemplate || isHiding">
      <div style="height:calc(100% - 40px);">
        <div class="header">摊位管理->摊位许可证</div>
        <div class="button_group">
          <el-button type="primary" icon="DocumentAdd" @click="addItem" v-if="permissionIsShow.add">新增</el-button>
          <el-input v-model="search" placeholder="许可证编号、经营户姓名" style="width: 250px;margin-right: 5px;margin-left: 10px"
            clearable />
          <el-button type="primary" icon="Search" style="margin-left: 5px" @click="reqData">搜索</el-button>
        </div>

        <el-table :data="tableData" :header-cell-style="{ background: '#f4f3f9' }" highlight-current-row
          style="width:100%;height:calc(92vh - 145px);background:#f4f3f9" border>
          <el-table-column align="center" prop="boothId" label="许可证编号"></el-table-column>
          <el-table-column align="center" prop="boothName" label="经营户姓名"></el-table-column>
          <el-table-column align="center" prop="phone" label="联系电话"></el-table-column>
          <el-table-column align="center" prop="fileUrl" label="经营户头像">
            <template v-slot="scope">
              <img :src="scope.row.fileUrl" style="width: 65px;height: 80px;">
            </template>
          </el-table-column>
          <el-table-column align="center" prop="occupiedArea" label="占道面积"></el-table-column>
          <el-table-column align="center" prop="boothAddress" label="经营地点"></el-table-column>
          <el-table-column align="center" prop="boothType" label="经营种类"></el-table-column>
          <el-table-column align="center" prop="validityDate" label="有效期"></el-table-column>
          <el-table-column align="center" prop="issueDate" label="发证日期"></el-table-column>
          <el-table-column align="center" prop="createTime" label="创建时间"></el-table-column>
          <el-table-column align="center" prop="operate" label="操作" fixed="right" width="200">
            <template v-slot="scope">
              <el-button type="primary" size="small" icon="Edit" @click.native.stop="editItem(scope.row)"
                v-if="permissionIsShow.edit" style="margin-left: 5px;">编辑</el-button>
              <el-button type="success" size="small" icon="View" @click.native.stop="previewItem(scope.row)"
                style="margin-left: 5px;">查看</el-button>
              <el-button type="primary" size="small" icon="Download"
                @click.native.stop="handleDownload(scope.row.pdf, scope.row.boothId)"
                style="margin-left: 5px;">下载</el-button>
              <el-button type="danger" size="small" icon="Delete" @click.native.stop="deleteItem(scope.row)"
                v-if="permissionIsShow.delete" style="margin-left: 5px;">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!--      分页1-->
      <div class="footer">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[5, 10, 20]"
          :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>
    <!--   文书查看界面   -->
    <div class="frameworkIn1" v-if="clickTemplate" :style="{ visibility: isHiding ? 'hidden' : 'visible' }">
      <div class="templateHeader">
        <span style="padding-bottom: 4px;">摊位许可证</span>
        <span style="float: right;padding-bottom: 6px;">
          <el-button type="danger" icon="Close" size="small" @click="closeTemplate()">
          </el-button>
        </span>
      </div>
      <iframe style="width:100%;height:calc(100% - 76px);border:none;" ref="iframe" :src="'./' + 202406251026"></iframe>
    </div>
    <!-- 新增和编辑弹窗 -->
    <el-dialog :title="isEdit ? '编辑' : '新增'" v-model="dialogVisible" width="50%" :close-on-click-modal="false"
      :before-close="handleBeforeClose" @close="closeDialog">
      <div v-loading="submitLoading" element-loading-text="正在生成中，请稍候..." element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="150px">
          <el-form-item label="许可证编号" prop="boothId">
            <el-input v-model="form.boothId" placeholder="请输入许可证编号(最多15位字母或数字)" maxlength="15"
              oninput="this.value = this.value.replace(/[^a-zA-Z0-9_-]/g, '')" clearable></el-input>
          </el-form-item>
          <el-form-item label="经营户姓名" prop="boothName">
            <el-input v-model="form.boothName" placeholder="请输入经营户姓名(限10个字符)" maxlength="10" clearable></el-input>
          </el-form-item>
          <el-form-item label="经营户头像" prop="fileUrl">
            <!-- 上传头像 -->
            <el-upload class="avatar-uploader" action="/api/related-file/uploadSign" :show-file-list="false"
              :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="form.fileUrl" :src="form.fileUrl" class="avatar">
              <div v-else class="avatar-uploader-icon">
                <Plus style="width: 28px;height: 28px;" />
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入联系电话" clearable></el-input>
          </el-form-item>
          <el-form-item label="占道面积" prop="occupiedArea">
            <el-input v-model="form.occupiedArea" placeholder="请输入占道面积(限10个字符)" maxlength="10" clearable></el-input>
          </el-form-item>
          <el-form-item label="经营地点" prop="boothAddress">
            <el-input v-model="form.boothAddress" placeholder="请输入经营地点(限20个字符)" maxlength="20" clearable></el-input>
          </el-form-item>
          <el-form-item label="经营品种" prop="boothType">
            <el-input v-model="form.boothType" placeholder="请输入经营品种(限20个字符)" maxlength="20" clearable></el-input>
          </el-form-item>
          <!-- 夏季上午时间 -->
          <el-form-item label="夏、秋上午时间" prop="sumMornStart">
            <el-select v-model="form.sumMornStart" placeholder="请选择开始时间（单位：时）" style="width: 35%;" clearable>
              <el-option v-for="item in mornOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            <span>&nbsp;-&nbsp;</span>
            <el-select v-model="form.sumMornEnd" placeholder="请选择结束时间（单位：时）" style="width: 35%;" clearable>
              <el-option v-for="item in mornOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <!-- 夏季下午时间 -->
          <el-form-item label="夏、秋下午时间" prop="sumAfterStart">
            <el-select v-model="form.sumAfterStart" placeholder="请选择开始时间（单位：时）" style="width: 35%;" clearable>
              <el-option v-for="item in afterOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            <span>&nbsp;-&nbsp;</span>
            <el-select v-model="form.sumAfterEnd" placeholder="请选择结束时间（单位：时）" style="width: 35%;" clearable>
              <el-option v-for="item in afterOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <!-- 春冬上午时间 -->
          <el-form-item label="春、冬上午时间" prop="sprMornStart">
            <el-select v-model="form.sprMornStart" placeholder="请选择开始时间（单位：时）" style="width: 35%;" clearable>
              <el-option v-for="item in mornOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            <span>&nbsp;-&nbsp;</span>
            <el-select v-model="form.sprMornEnd" placeholder="请选择结束时间（单位：时）" style="width: 35%;" clearable>
              <el-option v-for="item in mornOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <!-- 春冬下午时间 -->
          <el-form-item label="春、冬下午时间" prop="sprAfterStart">
            <el-select v-model="form.sprAfterStart" placeholder="请选择开始时间（单位：时）" style="width: 35%;" clearable>
              <el-option v-for="item in afterOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            <span>&nbsp;-&nbsp;</span>
            <el-select v-model="form.sprAfterEnd" placeholder="请选择结束时间（单位：时）" style="width: 35%;" clearable>
              <el-option v-for="item in afterOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <!-- 有效期 -->
          <el-form-item label="许可证失效日期" prop="validityDate">
            <el-date-picker v-model="form.validityDate" value-format="YYYY年MM月DD日" type="date" placeholder="请选择许可证失效日期">
            </el-date-picker>
          </el-form-item>
          <!-- 发证日期 -->
          <el-form-item label="发证日期" prop="issueDate">
            <el-date-picker v-model="form.issueDate" value-format="YYYY年MM月DD日" type="date" placeholder="请选择发证日期">
            </el-date-picker>
          </el-form-item>
        </el-form>
        <div style="text-align: right;">
          <el-button type="primary" @click="submitForm">确定</el-button>
          <el-button type="default" @click="closeDialog">取消</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 预览弹窗 -->
    <el-dialog title="查看摊位许可证" v-model="previewVisible" width="70%" :close-on-click-modal="false">
      <iframe :src="previewUrl" frameborder="0" style="width: 100%; height: 70vh;"></iframe>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";
import { Plus } from '@element-plus/icons-vue';
import axios from "axios";
import { stallIp } from "@/ipConfig/stallConfig";
export default {
  name: "BoothLicence",
  components: {
    Plus
  },
  data() {
    return {
      stallIp: stallIp,
      dialogVisible: false, // 弹窗是否显示
      isEdit: false,  // 是否启动编辑弹窗
      isHiding: false, // 是否隐藏文书
      submitLoading: false, // 保存加载状态
      form: {
        id: '',
        boothId: '', //许可证编号
        boothName: '', // 经营户姓名
        phone: '',  // 手机号
        occupiedArea: '', // 占道面积
        boothAddress: '', // 经营地点
        boothType: '', // 经营种类
        fileUrl: '', // 头像文件路径
        sumMornStart: '', // 夏秋上午开始时间
        sumMornEnd: '', // 夏秋上午结束时间
        sumAfterStart: '', // 夏秋下午开始时间
        sumAfterEnd: '', // 夏秋下午结束时间
        sprMornStart: '', // 春冬上午开始时间
        sprMornEnd: '', // 春冬上午结束时间
        sprAfterStart: '', // 春冬下午开始时间
        sprAfterEnd: '', // 春冬下午结束时间
        createTime: '', // 创建时间
        validityDate: '', // 有效期
        issueDate: '', // 发证日期
        qrCodePath: '', // 二维码文件路径
      },
      rules: {
        boothId: [{ required: true, message: '请输入摊位编号', trigger: 'blur' }],
        boothName: [{ required: true, message: '请输入经营户姓名', trigger: 'blur' }],
        fileUrl: [{ required: true, message: '请上传头像', trigger: 'blur' }],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
        ],
        occupiedArea: [{ required: true, message: '请输入占道面积', trigger: 'blur' }],
        boothAddress: [{ required: true, message: '请输入经营地点', trigger: 'blur' }],
        boothType: [{ required: true, message: '请输入经营种类', trigger: 'blur' }],
        validityDate: [{ required: true, message: '请输入许可证失效日期', trigger: 'blur' }],
        issueDate: [{ required: true, message: '请输入发证日期', trigger: 'blur' }],
      },

      // 上午时间选项
      mornOptions: [
        { value: '5', label: '5' },
        { value: '6', label: '6' },
        { value: '7', label: '7' },
        { value: '8', label: '8' },
        { value: '9', label: '9' },
        { value: '10', label: '10' },
        { value: '11', label: '11' },
        { value: '12', label: '12' },
      ],
      // 下午时间选项
      afterOptions: [
        { value: '13', label: '13' },
        { value: '14', label: '14' },
        { value: '15', label: '15' },
        { value: '16', label: '16' },
        { value: '17', label: '17' },
        { value: '18', label: '18' },
        { value: '19', label: '19' },
        { value: '20', label: '20' },
        { value: '21', label: '21' },
        { value: '22', label: '22' },
        { value: '23', label: '23' },
        { value: '24', label: '24' },
      ],


      clickTemplate: false,
      // 表格1
      currentPage: 1, //页码
      pageSize: 5, //页长
      total: 0,
      tableData: [],
      search: '', // 搜索许可证编号、经营户姓名

      previewVisible: false, // 预览弹窗是否显示
      previewUrl: '', // 预览文件路径

      // 登录用户信息
      loginUserInfo: {
        id: '',
        responsibleScope: '', //查询范围
        roleLevel: '', //角色等级
        unitId: '', //内设部门ID
        userRole: '', //角色ID
        permissions: [], // 按钮路径（数据库中的path）
      },
      // 按钮权限
      permissionIsShow: {
        add: false,
        edit: false,
        delete: false,
      },
    }
  },
  created() {
    const info = JSON.parse(localStorage.getItem("user"));
    this.loginUserInfo = {
      id: Number(info.id),
      responsibleScope: info.responsibleScope, //查询范围
      roleLevel: Number(info.roleLevel),
      unitId: Number(info.unitId),
      userRole: Number(info.userRole),
      permissions: info.permissions.filter(item => Number(item.menuId) === 34).map(item => item.path),
    }
    this.permissionIsShow = {
      add: this.loginUserInfo.permissions.includes('boothLicence-add'),
      edit: this.loginUserInfo.permissions.includes('boothLicence-edit'),
      delete: this.loginUserInfo.permissions.includes('boothLicence-delete'),
    }
    this.reqData(); //加载许可证数据
  },
  methods: {
    //分页请求许可证数据
    reqData() {
      request.get("/booth-licence/page", {
        params: {
          search: this.search,
          pageNum: this.currentPage,
          pageSize: this.pageSize,
        }
      }).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
      })
    },
    // 上传头像成功
    handleAvatarSuccess(res, file) {
      this.form.fileUrl = `api/file/download/${res.data.url}`;
    },
    // 上传头像前检查
    beforeAvatarUpload(file) {
      // 检查是否是图片
      const isPig = file.type === 'image/jpeg' || file.type === 'image/png';

      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isPig) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
      } else if (!isLt10M) {
        this.$message.error('上传头像图片大小不能超过 10MB!');
      }
      return isPig && isLt10M;
    },
    // 分页功能1
    handleSizeChange(val) {
      this.pageSize = val;
      this.reqData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.reqData();
    },
    // 初始化form
    initForm() {
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
      this.form = {}
    },
    handleBeforeClose(done) {
      if (this.submitLoading) {
        // 如果正在提交，不允许关闭
        return;
      }
      // 允许关闭，调用done()触发关闭逻辑
      done();
    },
    closeDialog() {
      this.initForm();
      this.dialogVisible = false;
    },

    //编辑
    editItem(val) {
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
      this.form = { ...val };
      this.isEdit = true;
      this.dialogVisible = true;
    },
    //新增许可证按钮
    addItem() {
      this.isEdit = false;
      this.dialogVisible = true;
      this.initForm();
    },
    submitForm() {
      // 校验提交表单
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          const fromData = { ...this.form }
          // 跳转页面URL
          fromData.jumpPageUrl = this.stallIp;
          request.post("/booth-licence/edit", fromData).then(res => {
            if (res.code == '200') {
              // 将生成的二维码路径赋值给表单
              fromData.qrCodePath = res.data.qrCodePath;
              this.form.qrCodePath = res.data.qrCodePath;
              this.form.id = res.data.id;
              // 创建文书时生成PDF
              fromData.createdGeneratePDF = true;

              window.getTemplateData = (callback) => {
                this.getTemplateData(fromData, callback);
              }
              window.closeAddItem = async (pdf) => {
                if (!pdf) {
                  this.$message({
                    type: "warning",
                    message: '系统错误，请联系管理员'
                  })
                  this.isHiding = false;
                  this.clickTemplate = false;
                  // 走删除
                  request.get("/booth-licence/delete/" + this.form.id).then(res => { })
                  this.submitLoading = false;
                  return;
                }
                await axios.post("/api/related-file/uploadPDF", pdf, {
                  params: {
                    id: this.form.id
                  },
                  headers: {
                    'Content-Type': 'multipart/form-data'
                  }
                }).then(req => {
                  if (req.data.code === '200') {
                    const pdfFromData = {
                      id: this.form.id,
                      qrCodePath: this.form.qrCodePath,
                      pdf: `api/file/download/${req.data.data}`,
                    }
                    request.post("/booth-licence/saveErCodeAndPDF", pdfFromData).then(res => {
                      if (res.code == '200') {
                        // 关闭弹窗
                        this.clickTemplate = false;
                        this.isHiding = false;
                        this.dialogVisible = false;
                        // 刷新表格数据
                        this.reqData();
                        // 提示用户操作成功
                        this.$message({
                          type: "success",
                          message: "操作成功"
                        })
                        this.submitLoading = false;
                      } else {
                        this.$message({
                          type: "warning",
                          message: '系统错误，请联系管理员'
                        })
                        this.isHiding = false;
                        this.clickTemplate = false;
                        // 走删除
                        request.get("/booth-licence/delete/" + this.form.id).then(res => { })
                        this.submitLoading = false;
                      }
                    })
                  } else {
                    this.$message({
                      type: "warning",
                      message: '系统错误，请联系管理员'
                    })
                    this.isHiding = false;
                    this.clickTemplate = false;
                    // 走删除
                    request.get("/booth-licence/delete/" + this.form.id).then(res => { })
                    this.submitLoading = false;
                  }
                })
              }
              this.isHiding = true;
              this.clickTemplate = true;
            } else if (res.code == '500') {
              this.$message({
                type: "warning",
                message: res.msg
              })
              this.submitLoading = false;
            } else {
              this.$message({
                type: "warning",
                message: '系统错误，请联系管理员'
              })
              this.submitLoading = false;
            }
          })
        } else {
          // 校验不通过，提示用户输入正确信息
          this.$message({
            type: 'error',
            message: '请输入正确的信息'
          });
        }
      });
    },
    previewItem(item) {
      this.previewUrl = item.pdf + '?t=' + new Date().getTime();
      this.previewVisible = true;
    },

    //下载
    handleDownload(pdf, boothId) {
      const link = document.createElement('a');
      link.href = pdf;
      link.download = '临时摊位许可证-' + boothId + '.pdf';
      link.click();
      setTimeout(() => {
        link.remove();
      }, 30000);
    },


    //删除
    deleteItem(item) {
      this.$confirm('是否确定删除本条数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showClose: false,
        type: 'warning'
      }).then(() => {
        request.get("/booth-licence/delete/" + item.id).then(res => {
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "删除成功"
            })
            this.reqData();
          } else {
            this.$message({
              type: "warning",
              message: "操作错误"
            })
          }
        })
      })
    },
    //获取文书数据
    getTemplateData: function (val, callback) {
      callback(val);
    },
  },
}
</script>

<style scoped>
/*   外框架   */
.framework1 {
  height: calc(100vh - 88px);
  width: calc(100vh - 200px);
  margin-left: 8px;
  border: solid 1px #D3D3D3;
}

/*   文书内框架   */
.frameworkIn1 {
  height: calc(100vh - 92px);
  width: 100%;
  border: solid 1px #D3D3D3;
}

/*   内框架   */
.framework2 {
  height: calc(100vh - 92px);
  border: solid 1px #D3D3D3;
}

/*   文书标题   */
.templateHeader {
  font-size: 19px;
  font-weight: bold;
  padding: 4px 20px;
  height: 30px;
  border: 1px solid #CCCCCC;
  background-color: #E0ECFF;
}

/*   文书底边   */
.templateFooter {
  text-align: center;
  margin-top: -4px;
  padding: 4px 20px;
  height: 30px;
  border: 1px solid #CCCCCC;
  background-color: #E0ECFF;
}

/*   表格大标题   */
.header {
  font-size: 16px;
  font-weight: bold;
  padding: 4px 20px;
  background-color: #D3D3D3;
}

/*   表格按键组   */
.button_group {
  padding: 4px 10px;
  background-color: #DDDDDD;
}

/*   表格翻页   */
.footer {
  padding: 4px 10px;
  background-color: #f4f3f9;
}

::v-deep .el-table__body tr.current-row>td {
  background: rgb(209, 236, 253) !important;
}

/** 头像上传器 */
:deep(.avatar-uploader .el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

:deep(.avatar-uploader .el-upload:hover) {
  border-color: #409EFF;
}

/* 上传图标容器样式 */
:deep(.avatar-uploader-icon) {
  font-size: 28px;
  color: #8c939d;
  width: 130px;
  height: 160px;
  display: flex;
  align-items: center;
  justify-content: center;
}


:deep(.avatar) {
  width: 130px;
  height: 160px;
  display: block;
}
</style>
